package com.github.tomakehurst.wiremock.db.utils;

import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.common.JsonException;
import com.github.tomakehurst.wiremock.db.entity.MultiMappingEntity;
import com.github.tomakehurst.wiremock.db.entity.StubMappingEntity;
import com.github.tomakehurst.wiremock.db.service.MultiMappingService;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import com.github.tomakehurst.wiremock.stubbing.StubMappingCollection;

import java.util.List;
import java.util.stream.Collectors;

public class StubMappingConverter {
    // 依赖MultiMappingService，用于查询关联的多Stub集合content
    private final MultiMappingService multiMappingService;

    // 构造器注入依赖
    public StubMappingConverter(MultiMappingService multiMappingService) {
        this.multiMappingService = multiMappingService;
    }

    /**
     * 业务模型（StubMapping） -> Entity（StubMappingEntity）
     * 承接原StubMappingService中的toEntity方法逻辑
     */
    public StubMappingEntity toEntity(StubMapping stubMapping, String contentId) {
        if (stubMapping == null) {
            throw new IllegalArgumentException("待转换的StubMapping不能为空");
        }
        if (stubMapping.getId() == null) {
            throw new IllegalArgumentException("StubMapping的ID不能为空");
        }

        StubMappingEntity entity = new StubMappingEntity();
        // 1. 基础字段：ID（UUID转字符串）
        entity.setId(stubMapping.getId().toString());
        // 2. 持久化标识
        entity.setIsPersistent(stubMapping.shouldBePersisted());
        // 3. 关联字段：contentId（关联多Stub集合）
        entity.setContentId(contentId);
        // 4. 扩展字段：demandId（从业务模型获取）
        entity.setDemandId(stubMapping.getDemandId());
        // 5. 扩展字段：createUserId（实际项目需从ThreadLocal等上下文获取，此处预留接口）
        entity.setCreateUserId(getCurrentUserId()); // 需实现getCurrentUserId()方法
        // 6. 其他字段：sanitizedUrl（从业务模型的RequestPattern获取）
        entity.setSanitizedUrl(stubMapping.getRequest() != null ? stubMapping.getRequest().getUrl() : "");
        // 7. originalFilename：默认null（无特殊需求可不设置）
        entity.setOriginalFilename(null);

        entity.setCreateUserId(stubMapping.getCreateUserId());

        return entity;
    }

    /**
     * Entity（StubMappingEntity） -> 业务模型（StubMapping）
     * 解析关联的多Stub集合content，融合扩展字段
     */
    public StubMapping toStubMapping(StubMappingEntity entity) {
        if (entity == null) {
            throw new IllegalArgumentException("待转换的StubMappingEntity不能为空");
        }
        String stubId = entity.getId();
        String contentId = entity.getContentId();

        try {
            // 1. 查询关联的MultiMapping（获取content）
            MultiMappingEntity multiEntity = multiMappingService.findByStubId(stubId); // 调用MultiMappingService的查询方法
            if (multiEntity == null) {
                throw new RuntimeException("Stub对应的扩展记录不存在：stubId=" + stubId + ", contentId=" + contentId);
            }

            // 2. 直接反序列化单个StubMapping的content（无需集合处理）
            StubMapping stubMapping = Json.read(multiEntity.getContent(), StubMapping.class);

            // 3. 融合Entity中的扩展字段（demandId、createUserId等）
            stubMapping.setDemandId(entity.getDemandId());
            stubMapping.setCreateUserId(entity.getCreateUserId());
            stubMapping.setPersistent(entity.getIsPersistent());
            stubMapping.setDirty(false);

            return stubMapping;
        } catch (Exception e) {
            throw new RuntimeException("转换StubMapping失败：stubId=" + stubId, e);
        }
    }

    /**
     * 批量转换：Entity列表 -> 业务模型列表
     */
    public List<StubMapping> batchToStubMapping(List<StubMappingEntity> entities) {
        if (entities == null || entities.isEmpty()) {
            return List.of();
        }
        return entities.stream()
                .map(this::toStubMapping)
                .collect(Collectors.toList());
    }

    /**
     * 私有工具方法：获取当前登录用户ID（实际项目需实现，如从ThreadLocal获取）
     */
    private String getCurrentUserId() {
        // 示例实现：实际需替换为真实的用户上下文逻辑（如UserContext.getCurrentUser().getId()）
        return "DEFAULT_USER"; // 临时占位，需根据项目认证框架调整
    }
}